package com.heima.behavior.service.Imp;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorServiceImp implements ApReadBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 阅读
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        ApBehaviorEntry behaviorEntry = creatBehaviorEntryMsg(dto);
        //1.检验参数文章id不能为空
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章的id不能为空");
        }
        //2.根据登录用户id或设备id查询行为实体（越读操作可不登录）
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        //3.判断阅读行为是否存在
        //阅读行为存在 修改count值+1
        if (readBehavior != null) {
            short count =(short)(readBehavior.getCount() + 1);
            Update update = new Update();
            update.set("count", count).set("createdTime", new Date()).set("updatedTime", new Date());
            //修改  完成阅读次数的更新
            mongoTemplate.updateFirst(query,update,ApReadBehavior.class);
        } else {
            //阅读行为不存在 创建新的
            readBehavior = new ApReadBehavior();
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setCount((short)1);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            //保存阅读行为
            mongoTemplate.save(readBehavior);

        }
        //===================================
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setArticleId(dto.getArticleId());
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE,JSON.toJSONString(mess));
        log.info("阅读行为 发送消息=={}", JSON.toJSONString(mess));
        return ResponseResult.okResult();
    }

    private ApBehaviorEntry creatBehaviorEntryMsg(ReadBehaviorDTO dto) {
        //获得用户token中的id检查是否处于登陆状态
        ApUser user = AppThreadLocalUtils.getUser();
        //对数据进行判空
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户未携带ID或未携带设备ID");
        }
        //调用
       // return  ApBehaviorEntryService(user.getId(),likesBehaviorDTO.getEquipmentId());
        return apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(),dto.getEquipmentId());
    }
}
